home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!sun2!ua302aa
- From: ua302aa@sun2.lrz-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: How to access memory allocated in function
- Date: 15 Jan 1996 13:43:47 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4ddlmj$av5@sparcserver.lrz-muenchen.de>
- References: <4ddbe3$so3@josie.abo.fi>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- csundqvi@abo.fi (Christoffer Sundqvist) writes:
-
- >Hello
-
- >How can i access memory allocated dynamically in a function after i leave the
- >function, something like this:
-
- You cannot, because pointers are passed by value like all other objects
- in C.
-
- >main()
- >{
- >int *p;
- >sub(p);
-
- No prototype for sub() has been seen, so sub() will be called as
- a function taking an unspecified number of parameters and returning
- int, i.e. as if sub() had been declared as "int sub();".
-
- This may be a problem because sub does not return an int.
-
- >}
-
- >void sub(int *p)
- >{
- > p = malloc(.....);
- >}
-
- If you want assigments to a variable passed to a function to have
- effect after the function returns, assigning to the function
- parameter is _not_ enough.
-
- Two persons once wrote a book about C. In this book they state
- that you should think about function parameters as conveniently
- initialized local variables of your function. Since the same
- two persons also "invented" the C programming language, maybe
- we should trust them.
-
- Consider:
-
- void
- sub(int n)
- {
- n = 4;
- }
-
- main()
- {
- int m;
-
- sub(m);
- return 0;
- }
-
- Would you expect m to be set to 4 after the call to sub()? This
- situation is very similar, if not identical, to the posted example.
-
- The most common approaches to pass back a value from a function
- to the caller are
-
- 1) return the value from the function or
- 2) pass a pointer to a variable to the function and let the
- function set that variable to the desired value.
-
- The second method mimics "call by reference", as known from other
- languages.
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
- | ua302aa@sunmail.lrz-muenchen.de
-